// 解决CLICK的300MS延迟
FastClick.attach(document.body);
let lrcbox = document.querySelector('.song-iner')
let myAudio = document.querySelector('#myAudio'),
  musicBtn = document.querySelector('.song-play'),
  lyricList = [],
  con = document.querySelector(' .song-turn'),
  songimg = document.querySelector('.song-img');

/* 处理播放时间和进度的 */
const format = function format(num) {
  let minutes = Math.floor(num / 60),
    seconds = Math.ceil(num - minutes * 60);
  if (minutes < 10) minutes = '0' + minutes;
  if (seconds < 10) seconds = '0' + seconds;
  return `${minutes}:${seconds}`;
};
const handleTimeAndRate = function handleTimeAndRate() {
  let { currentTime, duration } = myAudio;
  if (isNaN(currentTime) || isNaN(duration)) return;
  if (currentTime >= duration) {
    currentTime = 0;
  }
};
// 等待Audio加载完毕基础信息
myAudio.onloadedmetadata = handleTimeAndRate;
$sub.on('music', handleTimeAndRate);

//获取歌词
function exportTime() {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest
    xhr.open("GET", './lyric.json');
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let data = JSON.parse(xhr.responseText);
        resolve(data);
      }
    }
    xhr.send();
  })
}
exportTime().then(value => {
  return value.lyric;
})
  .then(lyric => {
    render(lyric);
  });
//绑定歌词
const render = function reder(lyric) {
  let arr = [];
  let lyr = lyric.replace(/\[(\d+):(\d+)\.(?:\d+)\](.*)/g, (_, minutes, seconds, text) => {
    arr.push({
      minutes,
      seconds,
      text
    });
  })
  console.log(arr);
  // 歌词绑定
  let str = ``;
  arr.forEach(item => {
    let {
      minutes,
      seconds,
      text
    } = item;
    str += `<p minutes="${minutes}" seconds="${seconds}">
       ${text}
     </p>`;
  });
  // console.log(str);
  lrcbox.innerHTML = str;
  lyricList = Array.from(lrcbox.querySelectorAll('p'));
}


let n = 0;
$sub.on('music', function () {
  let { currentTime, duration } = myAudio,
    [minutes, seconds] = format(currentTime).split(':'),
    H = lyricList[0].offsetHeight;
  // 从所有歌词中筛选出：和播放时间匹配的歌词集合 & 不匹配的集合
  // 从所有歌词中筛选出：和播放时间匹配的歌词集合 & 不匹配的集合
  // 一经发现匹配再处理
  let matchArr = [],
    matchNoneArr = [];
  lyricList.forEach(item => {
    let a = item.getAttribute('minutes'),
      b = item.getAttribute('seconds');
    if (a === minutes && b === seconds) {
      matchArr.push(item);
      return;
    }
    matchNoneArr.push(item);
  });
  if (matchArr.length > 0) {
    matchArr.forEach(item => item.classList.add('active'));
    matchNoneArr.forEach(item => item.classList.remove('active'));
    // 匹配的同时不要忘记：WRAPPER的挪动
    n += matchArr.length;
    if (n > 4) {
      lrcbox.style.transform = `translateY(${-(n - 4) * H}px)`;
    }
  }
  // 播放完毕的处理
  if (currentTime >= duration) {
    myAudio.pause();
    songimg.classList.remove('move');
    con.classList.remove('move');
    lrcbox.style.transform = `translateY(0)`;
    musicBtn.style.opacity = 1;
    lyricList.forEach(item => item.classList.remove('active'));
    n = 0;
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }
});



/* 音乐的播放和暂停 */
let timer = null;
musicBtn.onclick = function () {
  if (myAudio.paused) {
    // 当前是暂停的：我们让其播放
    myAudio.play();
    musicBtn.style.opacity = 0;
    songimg.classList.add('move');
    con.classList.add('move');
    if (!timer) {
      $sub.emit('music');
      timer = setInterval(() => {
        $sub.emit('music');
      }, 1000);
    }

  } else {
    // 当前是播放的：我们让其暂停
    myAudio.pause();
    songimg.classList.remove('move');
    con.classList.remove('move');
    musicBtn.style.opacity = 1;

    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }

};